package com.dm.intercept;


import com.alibaba.fastjson.JSON;
import com.dm.common.EmptyUtils;
import com.dm.common.PrintUtil;
import com.dm.dto.Dto;
import com.dm.dto.DtoUtil;
import com.dm.exception.ErrorCode;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 统一拦截控制器发异常处理
 */
public class ExceptionIntercept implements HandlerInterceptor {
    //@Resource
    //KafKaUtil kafKaUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    response.setHeader("Access-Control-Allow-Origin","*");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 控制方法之后异常处理
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        if(EmptyUtils.isNotEmpty(ex)){
            //kafKaUtil.sendErrorMessage(ex);
            response.setContentType("text/html;charset=UTF-8");
            PrintUtil printUtil=new PrintUtil(response);
            Dto dto= DtoUtil.returnFail(ErrorCode.COMMON_Exception.getErrorMessage(),ErrorCode.COMMON_Exception.getErrorCode());
            printUtil.print(JSON.toJSON(dto));
        }
    }
}
